package pers.jl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.jl.common.BaseContext;
import pers.jl.common.MyException;
import pers.jl.entity.*;
import pers.jl.mapper.OrdersMapper;
import pers.jl.service.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author luge
 * @since 2023-04-22
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private IShoppingCartService shoppingCartService;

    @Autowired
    private IAddressBookService addressBookService;

    @Autowired
    private IUserService userService;

    /**
     * 进行支付，生成订单
     * 操作三张表：订单表、订单明细表、购物车表
     * 先将订单插入对应表中
     * 再将订单明细插入对应表中
     * 清空购物车
     * @param orders
     */
    @Override
    public void submitForOrder(Orders orders) {
        // 1. 获取当前用户Id和用户、默认地址以及该用户购物车商品
        // 获取用户Id
        Long userId = BaseContext.getCurrentId();
        // 获取当前用户
        User user = userService.getById(userId);
        // 获取默认地址
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        // 获取购物车商品
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        // 如果用户购物车不存在或者购物车为空，不能下单
        if (shoppingCartList==null || shoppingCartList.size() == 0) {
            throw new MyException("用户购物车不存在或者购物车为空，不能下单!");
        }

        // 2. 数据处理
        // 生成订单号
        long orderId = IdWorker.getId();
        // 设置一个金额变量
        AtomicInteger amount = new AtomicInteger(0);
        // 将购物车转换成订单明细
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            // 将购物车商品数量和金额累乘后再累加
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        // 给订单设置值
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        // 3. 向订单表插入数据，一条数据
        this.save(orders);

        // 4. 向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        // 5. 清空购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
    }

    /**
     * 订单数据分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Orders> pageForOrder(int page, int pageSize) {

        // 1. 构造分页构造器
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        // 2. 构造条件构造器，按下单时间降序
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> pageback = this.page(ordersPage, ordersLambdaQueryWrapper);
        // 3. 返回结果
        return pageback;
    }
}
